package com.atguigu.chapter07.timer;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/20 10:15
 */
public class Flink01_Timer {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 如果水位值超过10, 则注册定时器, 发出水位预警
                    if (value.getVc() > 10) {
                        long now = System.currentTimeMillis();  // 1000
                        // 当前时间5s之后触发定时器
                        ctx.timerService().registerProcessingTimeTimer(now + 5000);
                    }
                
                }
            
                // 当定时器触发的时候, 会回调这个方法
                @Override
                public void onTimer(long timestamp, // 定时器的时间
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect("红色预警: " + ctx.getCurrentKey() + " 水位超过10");
                }
            })
            .print();
    
        env.execute();
    }
}
